
package org.apache.solr.update;

import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;

public class DeleteUpdateCommand extends UpdateCommand {

    public String id;    // external (printable) id, for delete-by-id
    public String query; // query string for delete-by-query
    public BytesRef indexedId;
    public int commitWithin = -1;

    public DeleteUpdateCommand(SolrQueryRequest req) {
        super(req);
    }

    @Override
    public String name() {
        return "delete";
    }

    public boolean isDeleteById() {
        return query == null;
    }

    public void clear() {

        id = null;
        query = null;
        indexedId = null;
        version = 0;
    }

    /**
     * Returns the indexed ID for this delete. The returned BytesRef is retained
     * across multiple calls, and should not be modified.
     */
    public BytesRef getIndexedId() {

        if (indexedId == null) {
            IndexSchema schema = req.getSchema();
            SchemaField sf = schema.getUniqueKeyField();
            if (sf != null && id != null) {
                indexedId = new BytesRef();
                sf.getType().readableToIndexed(id, indexedId);
            }
        }
        return indexedId;
    }

    public String getId() {

        if (id == null && indexedId != null) {
            IndexSchema schema = req.getSchema();
            SchemaField sf = schema.getUniqueKeyField();
            if (sf != null) {
                CharsRef ref = new CharsRef();
                sf.getType().indexedToReadable(indexedId, ref);
                id = ref.toString();
            }
        }
        return id;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public void setIndexedId(BytesRef indexedId) {
        this.indexedId = indexedId;
        this.id = null;
    }

    public void setId(String id) {
        this.id = id;
        this.indexedId = null;
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder(super.toString());
        if (id != null) {
            sb.append(",id=").append(getId());
        }
        if (indexedId != null) {
            sb.append(",indexedId=").append(getId());
        }
        if (query != null) {
            sb.append(",query=`").append(query).append('`');
        }
        sb.append(",commitWithin=").append(commitWithin);
        sb.append('}');

        return sb.toString();
    }
}
